<?php
class controller_RegisterController {
    private $view;
    private $args;

    public function setView(View $view) {
        $this->view = $view;
        return $this;
    }

    public function setArgs($args = null) {
        if(null != $args) {
            $this->args = $args;
        }
        return $this;
    }

    public function run() {
        
        if(empty($this->args['action'])) {
            $this->redir();
        } else {
            switch ($this->args['action']) {

                case 'index':
                    $this->index();
                    break;

                case 'save':
                    $this->save();
                    break;

                default:
                    $this->redir();
            }
        }
    }

    public function index() {
        $user = model_UserMapper::getCurrentUser();
        if(null == $user->getId()) {
            $this->view->setRenderTemplate("user/register.phtml");
        } else {
            $this->view->message = 'Вы уже зарегистрированы, зачем же вам ещё раз?!';
            $this->view->setRenderTemplate("error.phtml");
        }
    }

    public function save() {


        $user = model_UserMapper::getCurrentUser();
        $mapper = new model_UserMapper();
        if(null != $user) {

            $post = model_ConfigMapper::validate($_POST);
            //удаляем их пришедшего поста все инъекции и лишние пробелы
            
            if('' != $post['username']) {
                $mapper->validateReg($post);
                //если приходит юзернейм, то проверяем его валидейтом (совпадение паролей/наличие юзера с таким же именем)
                //если всё ок, то сохраняем.

                if (null == $mapper->getMessage()) {

                    $salt = model_ConfigMapper::getSalt(10);
                    $password = md5($salt.$post['password']);

                    $model = new model_UserModel();
                    $model->setUsername($post['username'])
                            ->setPassword($password)
                            ->setSalt($salt)
                            ->setRole('user')
                            ->setKarma(100)
                            ->setSex($post['sex'])
                            ->setName($post['name'])
                            ->setSurname($post['surname'])
                            ->setAvatar(null)
                            ->setAbout($post['about'])
                            ->setAge($post['age']);

                    $mapper->save($model);
                    $userId = mysql_insert_id();

                    if ('' != $_FILES['file']['name']) {

                        $uploaddir = 'stuff/images/saved/';
                        $filename = model_ConfigMapper::getSalt(10);
                        $uploadfile = $uploaddir.basename($filename);

                        if ( false == move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile.'.jpg')) {
                            $this->view->message = 'Ошибка при загрузке файла!';
                            $this->view->oneModel = new model_UserModel();
                            $this->view->oneModel->setUsername($post['username']);
                            $this->view->setRenderTemplate("user/register.phtml");
                            return;
                        }
                        $photoMapper = new model_PhotoMapper();
                        $photoModel = new model_PhotoModel();
                        $photoModel->setTitle(null)
                                ->setName($filename)
                                ->setOwner($userId);

                        $photoMapper->save($photoModel);
                        $id = mysql_insert_id();

                        $mapper->saveAvatar($id, $userId);
                    }
                }

                $this->view->message = $mapper->getMessage();

                if (empty ($this->view->message)) {
                    $userMapper = new model_UserMapper();
                    $userMapper->fastLogin($model, $userId);

                    $this->view->link = '?controller=user&action=index&id='. $userId ;
                    $this->view->setRenderTemplate("redirect.phtml");
                    return;
                } else {
                    $this->view->oneModel = new model_UserModel();
                    $this->view->oneModel->setUsername($post['username'])
                            ->setPassword($post['password'])
                            ->setName($post['name'])
                            ->setSurname($post['surname'])
                            ->setAbout($post['about'])
                            ->setAge($post['age']);
                    $this->view->setRenderTemplate("user/register.phtml");
                    return;
                }
            } else {
                $this->view->oneModel = new model_UserModel();
                $this->view->oneMode->setPassword($post['password'])
                        ->setName($post['name'])
                        ->setSurname($post['surname'])
                        ->setAbout($post['about']);
                $this->view->message = 'Не указан логин!';
                $this->view->setRenderTemplate("user/register.phtml");
                return;
            }
            $this->view->setRenderTemplate("user/register.phtml");
        } else {
            $this->view->message = 'Вы уже зарегистрированы, зачем же вам ещё раз?!';
            $this->view->setRenderTemplate("error.phtml");
        }
    }

    public function redir(){
        $this->view->setRenderTemplate("redirect.phtml");
    }
}